package com.caird.pmp.iot;

import com.caird.common.utils.DataTypeUtils;
import com.caird.pmp.iot.message.MessageBase;
import com.caird.pmp.iot.server.BbChannelManager;
import com.caird.pmp.iot.utils.Utils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

@Slf4j
public class RedisMessageListener implements MessageListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private BbChannelManager bbChannelManager;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        RedisSerializer<?> serializer = redisTemplate.getValueSerializer();
        MessageBase sm = (MessageBase) serializer.deserialize(message.getBody());
        sm.setSimNo(Utils.toSimNo(sm.getSimNo()));
        Channel channel = bbChannelManager.get(sm.getSimNo());
        if (null != channel) {
            sm.setFlowNo(BbChannelManager.getFlowNo(channel));
            ByteBuf byteBuf = sm.encode();
            log.info("发送：" + DataTypeUtils.byteBuf2HexString(byteBuf.resetReaderIndex()));
            channel.writeAndFlush(byteBuf);
        }
    }
}
